package com.warthur.vertx.demo.common;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.warthur.vertx.demo.common.enums.ErrorCode;
import com.warthur.vertx.demo.excepton.SystemException;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.RoutingContext;
import lombok.Data;
import lombok.experimental.Accessors;

import java.io.Serializable;

/**
 * @author warthur
 * @date 2019/10/07
 */
@Data
public class Response implements Serializable {
    private static final long serialVersionUID = 3298132694646370747L;

    private boolean success;
    private Integer code;
    private String message;
    @JsonInclude(JsonInclude.Include.NON_NULL)
    private Object data;

    @JsonIgnore
    private RoutingContext context;

    public Response(RoutingContext context) {
        this.context = context;
    }

    public Boolean getSuccess() {
        return code == 0;
    }

    public Boolean isSuccess() {
        return success;
    }

    public Response success() {

        this.code = ErrorCode.REQUEST_SUCCESS.getCode();
        this.message = ErrorCode.REQUEST_SUCCESS.getMsg();

        return this;
    }

    public Response errorCode(ErrorCode errorCode) {

        this.code = errorCode.getCode();
        this.message = errorCode.getMsg();

        return this;
    }

    public Response message(String message) {
        this.code = ErrorCode.REQUEST_ERROR.getCode();
        this.message = message;

        return this;
    }

    public Response statusCode(int statusCode) {
        if (this.context == null) {
            throw new SystemException("非法的参数");
        }
        this.context.response().setStatusCode(statusCode);
        return this;
    }

    public void body() {
        body(null);
    }

    public void body(Object data) {

        if (this.code == null) {
            success();
        }

        this.data = data;
        this.success = code == 0;

        this.context.response().end(this.toJsonString());
    }

    public String toJsonString() {
        return JsonObject.mapFrom(this).toString();
    }
}
